package com.heiyu.api.controller;

import com.google.common.collect.Lists;
import com.heiyu.api.request.ActivityJoinRequest;
import com.heiyu.api.request.ActivityLoginRequest;
import com.heiyu.api.response.*;
import com.heiyu.api.response.model.*;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.utils.CacheKey;
import com.heiyu.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(description = "火币活动相关接口")
@RestController
@RequestMapping("/api/v3/activity")
public class ActivityController extends ApiBaseController {


    @Autowired
    private ActivityInfoMapper activityInfoMapper;
    @Autowired
    private UserActivityInfoMapper userActivityInfoMapper;
    @Autowired
    private UserInviteMapper userInviteMapper;
    @Autowired
    private UserBalanceSeqMapper userBalanceSeqMapper;
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    @Autowired
    private UserBalanceTypeMapper userBalanceTypeMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private MessageInfoMapper messageInfoMapper;

    @ApiOperation(value = "status/get", notes = "获取用户当前状态")
    @ApiImplicitParam(name = "activityId", value = "活动主键")
    @GetMapping("status/get")
    public ActivityStatusGetResponse status(@RequestParam Long activityId) {
        ActivityStatusGetResponse response = new ActivityStatusGetResponse();
        response.setData(new ActivityStatusGetModel());
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        } else {
            ActivityInfo info = this.activityInfoMapper.selectPrimary(activityId);
            if(info == null || info.getCreatedTime().before(info.getBeginTime())){
                response.getData().setIsEnd("1");
            }else{
                response.getData().setIsEnd("0");
                //判断用户是否参与该活动
                UserActivityInfo userActivityInfo = new UserActivityInfo();
                userActivityInfo.setActivityId(activityId);
                userActivityInfo.setUserId(userInfo.getId());
                List<UserActivityInfo> list = this.userActivityInfoMapper.selectList(userActivityInfo);
                if (CollectionUtils.isEmpty(list)) {
                    response.getData().setIsNew("1");
                } else {
                    response.getData().setIsNew("0");
                }
            }
            response.success();
        }
        return response;
    }

    @ApiOperation(value = "get", notes = "获取活动信息")
    @ApiImplicitParam(name = "activityId", value = "活动主键")
    @GetMapping("get")
    public ActivityInfoGetResponse get(@RequestParam Long activityId) {
        ActivityInfoGetResponse response = new ActivityInfoGetResponse();
        response.setData(new ActivityInfoGetModel());
        ActivityInfo activityInfo = this.activityInfoMapper.selectPrimary(activityId);
        if (activityInfo != null) {
            response.getData().setId(activityInfo.getId());
            response.getData().setBeginTime(activityInfo.getBeginTime().getTime());
            response.getData().setEndTime(activityInfo.getEndTime().getTime());
            response.getData().setContent(activityInfo.getContent());
            response.getData().setName(activityInfo.getName());
            response.getData().setStatus(activityInfo.getStatus());
            response.success();
        } else {
            response.error("活动信息不存在·");
        }
        return response;
    }

    @ApiOperation(value = "join/put", notes = "参与活动")
    @PostMapping("join/put")
    public CommonResponse joinPut(@RequestBody ActivityJoinRequest request) {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        } else {
            UserActivityInfo userActivityInfo = new UserActivityInfo();
            userActivityInfo.setUserId(userInfo.getId());
            userActivityInfo.setActivityId(request.getActivityId());
            List<UserActivityInfo> list = this.userActivityInfoMapper.selectList(userActivityInfo);
            if (CollectionUtils.isEmpty(list)) {
                userActivityInfo.setCreatedTime(new Date());
                userActivityInfo.setModifyTime(new Date());
                userActivityInfo.setIsDeleted("0");
                this.userActivityInfoMapper.insert(userActivityInfo);
                ActivityInfo activityInfo = this.activityInfoMapper.selectPrimary(request.getActivityId());
                //账户增加10个yee
                if(request.getActivityId()==1l&&activityInfo.getBeginTime().before(userInfo.getCreatedTime())){
                    UserBalance balance = new UserBalance();
                    balance.setUserId(userInfo.getId());
                    balance.setAccountType(2l);
                    List<UserBalance> balanceList = this.userBalanceMapper.selectList(balance);
                    if(CollectionUtils.isEmpty(balanceList)){
                        balance.setCreatedTime(new Date());
                        balance.setModifyTime(new Date());
                        balance.setIsDeleted("0");
                        balance.setVersion(0l);
                        balance.setLockBalance(0l);
                        balance.setStatus("1");
                        balance.setBalance(10*100000l);
                        this.userBalanceMapper.insert(balance);
                    }else{
                        balance = balanceList.get(0);
                        balance.setBalance(balance.getBalance()+10*100000l);
                        this.userBalanceMapper.updateById(balance);
                    }
                    UserBalanceSeq seq = new UserBalanceSeq();
                    seq.setBalanceId(balance.getId());
                    seq.setActivityId(request.getActivityId());
                    seq.setCreatedTime(new Date());
                    seq.setModifyTime(new Date());
                    seq.setIsDeleted("0");
                    seq.setNum(10*100000l);
                    this.userBalanceSeqMapper.insert(seq);
                }
                response.success();
            } else {
                response.error("您已参加过该活动");
            }
        }
        return response;
    }


    @ApiOperation(value = "user/list", notes = "获取活动邀请用户信息")
    @GetMapping("user/list")
    public ActivityUserListResponse userList(@RequestParam Long activityId, @RequestParam Integer pageIndex, @RequestParam Integer pageSize) {
        ActivityUserListResponse response = new ActivityUserListResponse();
        UserInfo userInfo = getUser();
        ActivityInfo activityInfo = this.activityInfoMapper.selectPrimary(activityId);
        response.setData(new ActivityUserListModel());
        response.getData().setList(Lists.newArrayList());
        if (userInfo == null) {
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        } else if (activityInfo == null) {
            response.error("活动信息不存在");
        } else {
            Map<String, Object> param = PageUtils.newParam(pageIndex, pageSize);
            param.put("activityId", activityId);
            param.put("userId", userInfo.getId());
            List<UserInvite> list = this.userInviteMapper.page(param);
            if (!CollectionUtils.isEmpty(list)) {
                ActivityUserInfo model;
                for (UserInvite invite : list) {
                    model = new ActivityUserInfo();
                    model.setStatus(invite.getStatus());
                    model.setUserInfo(invite.getInviteUserInfo());
                    response.getData().getList().add(model);
                }
            }
            response.success();
        }

        return response;
    }

    @ApiOperation(value = "prize/list", notes = "获取活动奖励列表")
    @GetMapping("prize/list")
    public ActivityPrizeListResponse prizeList(@RequestParam Long activityId, @RequestParam Integer pageIndex, @RequestParam Integer pageSize) {
        ActivityPrizeListResponse response = new ActivityPrizeListResponse();
        response.setData(new ActivityPrizeListModel());
        response.getData().setList(Lists.newArrayList());
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        } else {
            UserBalanceSeq balance = new UserBalanceSeq();
            balance.setBalanceId(userInfo.getId());
            balance.setActivityId(activityId);
            List<Map<String, Object>> list = userBalanceSeqMapper.groupByActivity(balance);
            if (!CollectionUtils.isEmpty(list)) {
                UserBalanceSeqInfo model;
                UserBalance userBalance;
                UserBalanceType userBalanceType;
                for (Map<String, Object> map : list) {
                    userBalance = this.userBalanceMapper.selectPrimary(Long.valueOf(map.get("balanceId").toString()));
                    userBalanceType = this.userBalanceTypeMapper.selectPrimary(userBalance.getAccountType());
                    model = new UserBalanceSeqInfo();
                    model.setPrizeName(userBalanceType.getTypeName());
                    model.setPrizeNum(Long.valueOf(map.get("num").toString()) / 10000 + "");
                    response.getData().getList().add(model);
                }
            }
            response.success();
        }
        return response;
    }

    @ApiOperation(value = "login", notes = "活动注册登录")
    @PostMapping("login")
    public CommonResponse activityLogin(@RequestBody ActivityLoginRequest request) {
        CommonResponse response = new CommonResponse();
        //判断用户是否存在
        UserInfo userInfo = new UserInfo();
        userInfo.setTelphone(request.getTelphone());
        List<UserInfo> list = this.userInfoMapper.selectList(userInfo);
        if (!CollectionUtils.isEmpty(list)) {
            response.error("用户已存在");
        } else {
            UserInvite invite = new UserInvite();
            invite.setInviteUserInfo(request.getTelphone());
            List<UserInvite> inviteList = this.userInviteMapper.selectList(invite);
            if (!CollectionUtils.isEmpty(inviteList)) {
                response.error("您已注册成功");
            } else {
                String verifyCode = redisUtils.get(CacheKey.VERIFY_CODE + request.getTelphone());
                if (StringUtils.isEmpty(verifyCode)) {
                    response.error("验证码失效");
                    return response;
                }
                if (!verifyCode.equals(request.getVerifyCode())) {
                    response.error("验证码错误");
                    return response;
                }
                redisUtils.del(CacheKey.VERIFY_CODE + request.getTelphone());
                invite.setUserId(request.getUserId());
                invite.setActivityId(request.getActivityId());
                invite.setCreatedTime(new Date());
                invite.setModifyTime(new Date());
                invite.setIsDeleted("0");
                invite.setStatus("1");
                this.userInviteMapper.insert(invite);
                response.success();
            }
        }
        return response;
    }

    @ApiOperation(value = "verify/code/get", notes = "活动发送验证码")
    @GetMapping(value = "verify/code/get")
    public CommonResponse ActivityVerifyCodeGet(@RequestParam String telphone) {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = new UserInfo();
        userInfo.setTelphone(telphone);
        List<UserInfo> list = this.userInfoMapper.selectList(userInfo);
        if (!CollectionUtils.isEmpty(list)) {
            response.error("用户已存在");
        } else {
            UserInvite invite = new UserInvite();
            invite.setInviteUserInfo(telphone);
            List<UserInvite> inviteList = this.userInviteMapper.selectList(invite);
            if (!CollectionUtils.isEmpty(inviteList)) {
                response.error("用户已存在");
            } else {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setToTelphone(telphone);
                messageInfo.setParams(RandomStringUtils.random(4, false, true));
                messageInfo.setContent("［链码］您的验证码是{param1},有效时间5分钟。");
                messageInfo.setStatus("0");
                messageInfo.setCreatedTime(new Date());
                messageInfo.setModifyTime(new Date());
                messageInfo.setIsDeleted("0");
                messageInfo.setSendTime(new Date());
                this.messageInfoMapper.insert(messageInfo);
                this.redisUtils.set(CacheKey.VERIFY_CODE + telphone, messageInfo.getParams());
                response.success();
            }
        }
        return response;
    }

    @ApiOperation(value = "share/info/get", notes = "获取活动分享信息")
    @GetMapping(value = "share/info/get")
    public ActivityShareInfoResponse shareInfoGet(@RequestParam Long activityId) {
        ActivityShareInfoResponse response = new ActivityShareInfoResponse();
        response.setData(new ActivityShareInfo());
        ActivityInfo activityInfo = this.activityInfoMapper.selectPrimary(activityId);
        if (activityInfo == null) {
            response.error("活动不存在");
            return response;
        }
        UserInfo userInfo = getUser();
        if(userInfo == null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        //获取用户黑域币账户信息
        UserBalance balance = new UserBalance();
        balance.setAccountType(1l);
        balance.setUserId(userInfo.getId());
        List<UserBalance> list = this.userBalanceMapper.selectList(balance);
        if(CollectionUtils.isEmpty(list)){
            response.getData().setBalance("0.00000");
        }else{
            response.getData().setBalance(list.get(0).getBalance()/100000+"");
        }
        userInfo.setNickName(null);
        //获取活动名称
        response.getData().setTitle(activityInfo.getName());
        response.getData().setActivityUrl(activityInfo.getTargetUrl()+"?userId="+userInfo.getId()+"&activityId="+activityId+"&userName="+getNickName(userInfo));
        response.getData().setLogoUrl("http://cdn-2.heiyu.pro/lianma_www/assets/img/logo3.0.png");
        response.getData().setContent(activityInfo.getContent());
        response.success();
        return response;
    }

}
